﻿using SugarRedis;
using System;
using System.Collections.Generic;
using System.Text;

namespace CacheAttribute.Utils
{
    public class RedisCahceUtil : ICacheable
    {

        private static SugarRedisClient client;

        //使用一个饿汉的单例模式
        private static RedisCahceUtil instance;

        //私有的构造函数,初始化一下SugarRedisClient
        private RedisCahceUtil(String config = null) {

            if (!string.IsNullOrEmpty(config))
                client = new SugarRedisClient(config);
            else
                client = new SugarRedisClient();

        }

        public static RedisCahceUtil GetInstance()
        {
            if (instance == null)
            {
                instance = new RedisCahceUtil();
                return instance;
            }
            else
                return instance;
        }

        public bool Exist(string Key)
        {
            return client.Exists(Key);
        }

        public T Get<T>(string key)
        {
            return client.Get<T>(key);
        }

        public T GetGen<T>(string key)
        {
            return client.Get<T>(key);
        }

        public object Get(string key)
        {
            return client.Get(key);
        }

        public bool Remove(string Key)
        {
            try
            {
                client.Remove(Key);
                return true;
            }
            catch(Exception e)
            {
                return false;
            }
            
        }

        public bool RemovePattern(string Pattern)
        {
            try
            {
                client.RemoveCacheRegex(Pattern);
                return true;
            }catch(Exception e)
            {
                return false;
            }
        }

        public bool Set(string key, object obj, int Expire = 1800)
        {
            
            return client.Set(key, obj, Expire);
        }
    }
}
